package com.smf.lsc.authorization.security.captcha.controller;

import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.Producer;
import com.smf.lsc.authorization.security.captcha.util.CodeProperties;
import com.smf.lsc.authorization.security.util.Result;
import com.smf.lsc.authorization.security.util.Result.FlagValue;

import lombok.extern.slf4j.Slf4j;

/**
 * 验证码controller
 * Created on 2021/11/19.
 *
 * @author ln
 * @since 1.0
 */
@Slf4j
@RestController
@RequestMapping("/code")
public class CodeController {
	
	@Autowired
    private Producer captchaProducer = null;
	
	@Autowired
	private CodeProperties codeProperties;
	
	@Autowired
    private RedisTemplate<String, String> redisTemplate;
	
	@GetMapping("/kaptcha")
    public void getKaptchaImage(String codeRandom,HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
//        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        redisTemplate.opsForValue().set(codeRandom, capText, 60, TimeUnit.SECONDS);
        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
	
	@GetMapping("/kaptchaflag")
    public Result<Boolean> getKaptchaFlag() throws Exception {
		Result result = new Result();
		result.setMessage("获取验证码启用标识成功!");
		result.setCode(0);
		result.setFlag(FlagValue.SUCCESS);
		result.setData(codeProperties.isEnable());
		return result;
    }
}
